/**
 * @DESC choose image & preivew get image info&save image to photo album
 * ** */
const config = require('../../../bubaocloud/config.js');
const fileType = require('../../../utils/fileType.js').getType;
const app = getApp();
function getFileTypeSrc(fileName) {
  let fileTypes = fileType(fileName);
  return {
    src: `${config.host.rest}image/type/${fileTypes.typeName}.png`,
    typeName: fileTypes.typeName,
    typeNum: fileTypes.typeNum,
    type: fileTypes.type
  };
};

const image = {
  chooseImage(data = {}) {
    return new Promise((resolve, reject) => {
      wx.chooseImage({
        count: data.count ? data.count : 9,
        sizeType: data.sizeType ? data.sizeType : ['original', 'compressed'],
        sourceType: data.sourceType ? data.sourceType : ['album', 'camera'],
        success: function (res) {
          let tempFiles = res.tempFiles;
          for (let i in tempFiles) {
            let fileInfo = getFileTypeSrc(tempFiles[i].path);
            tempFiles[i].typeSrc = fileInfo.src;
            tempFiles[i].fileInfo = fileInfo;
            tempFiles[i].fileName = `${new Date().getTime() + i}.${fileInfo.type}`;
          }
          resolve({ tempFiles, tempFilePaths: res.tempFilePaths })
        },
        fail: function (res) { reject(res) },
        complete: function (res) { },
      })
    })
  },
  /**
   * @desc property 显示属性
   */

  previewImage(imageList, current = 0, property = false) {
    return new Promise((resolve, reject) => {
      if (property) {
        let previewList = [];
        for (let i in imageList) {
          previewList.push(imageList[i][property]);
        }
        wx.previewImage({
          current: previewList[current],
          urls: previewList,
          success: function (res) { resolve(res) },
          fail: function (res) { reject(res) },
          complete: function (res) { },
        })

      } else {
        wx.previewImage({
          current: imageList[current],
          urls: imageList,
          success: function (res) { resolve(res) },
          fail: function (res) { reject(res) },
          complete: function (res) { },
        })
      }
    })
  },

  getImageInfo(src) {
    return new Promise((resolve, reject) => {
      wx.getImageInfo({
        src: src,
        success: function (res) { resolve(res) },
        fail: function (res) { reject(res) },
        complete: function (res) { },
      })

    })
  },

  /**
   * @desc 选择分享照片
   */
  chooseSharePhoto() {
    return new Promise((resolve, reject) => {
      image.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
      }).then((res) => {
        resolve();
        app.sharePhoto = res.tempFiles[0];
        wx.navigateTo({
          url: '../sharePhoto/sharePhoto',
        });
      })
        .catch(err => {
          console.log(55555, err);
          reject(err);
        })
    })
  }

}

module.exports = image